package com.suliao.web.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.suliao.common.base.PageFactory;
import com.suliao.common.base.Result;
import com.suliao.common.base.UserContext;
import com.suliao.common.util.CryPtoUtil;
import com.suliao.common.util.SessionUtil;
import com.suliao.home.entity.industry.*;
import com.suliao.home.entity.product.TypeDO;
import com.suliao.home.entity.sys.AreaDO;
import com.suliao.home.entity.sys.FileDO;
import com.suliao.home.service.industry.*;
import com.suliao.home.service.product.TypeService;
import com.suliao.home.service.sys.AreaService;
import com.suliao.home.service.sys.FileService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: miaowenbin
 * @Description:产业展-展商
 * @Date: create in 2020/12/18 14:12
 */
@RequestMapping(value = "exhibitShop")
@Controller
public class IndustryExhibitShopController {

    @Reference
    private AreaService areaService;

    @Autowired
    private CryPtoUtil cryPtoUtil;

    /**
     * 共享工具类
     */
    @Autowired
    private SessionUtil sessionUtil;

    @Reference
    private ExhibitorService exhibitorService;

    @Reference
    private TypeService typeService;

    @Reference
    private TopicService topicService;

    @Reference
    private ApplicationClassService applicationClassService;

    @Reference
    private CompanyExhibitorInformationService companyExhibitorInformationService;

    @Reference
    private FileService fileService;

    @Reference
    private ExhibitService exhibitService;

    /**
     * 展商列表
     * @param
     * @param province
     * @param city
     * @param district
     * @param page
     * @param
     * @return
     */
    @RequestMapping(value = "/list")
    public ModelAndView list(
            @RequestParam(value = "province",defaultValue = "") String province,
            @RequestParam(value = "city",defaultValue = "") String city,
            @RequestParam(value = "district",defaultValue = "") String district,
            @RequestParam(value = "productTitle",defaultValue = "")String productTitle,
            @RequestParam(value = "page",defaultValue = "") Integer page,
            String banPositionBack){
        ModelAndView modelAndView=new ModelAndView("tradeShow/exhibitShop");
        modelAndView.addObject("banPositionBack",banPositionBack);
        modelAndView.addObject("productTitle",productTitle);
        modelAndView.addObject("province",province);
        modelAndView.addObject("city",areaService.getAreaName(city));
        modelAndView.addObject("district",areaService.getAreaName(district));

        // 获取登录人信息
        UserContext userContext = sessionUtil.getUserContext();
        modelAndView.addObject("userinfo", userContext);
        //用于首页样式选中样式回显
        String ProductName = "展商";
        modelAndView.addObject("ProductName",ProductName);

        UserContext user = sessionUtil.getUserContext();
        if(user==null){
            Integer resFlag = 0;
            modelAndView.addObject("resFlag", resFlag);

        }else {
            Integer userId = user.getUserId();

            //查询展商关注
            List<ExhibitorDO> userAttentionList = exhibitorService.findExhibitorAttention(userId);

            Integer resFlag = 0;
            if (userAttentionList.size() > 0) {
                resFlag = 1;
            }
            modelAndView.addObject("resFlag", resFlag);
            modelAndView.addObject("userAttentionList", userAttentionList);
        }
        if(user == null){
            System.out.println("----------");
        }else{
            Integer corpId = user.getCompanyId();
            //查询塑金余额
            String plasticGoldList = "0.00";
            if(corpId == null){
                modelAndView.addObject("plasticGoldList",plasticGoldList);
            }else{
                /*EnterpriseInfoDto enterpriseInfoDto = new EnterpriseInfoDto();
                enterpriseInfoDto.setUuid(corpId);
                plasticGoldList = industryExhibitorService.findAllPlasticGolds(enterpriseInfoDto);
                modelAndView.addObject("plasticGoldList",plasticGoldList);*/
            }
        }
        return modelAndView;

    }
    /**
     * 省市区三级联动根据parentId查询
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/area")
    @ResponseBody
    public void getAreaList(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setContentType("text/xml;Charset=UTF-8");
        int parentId = Integer.parseInt(request.getParameter("parentId"));
        List<AreaDO> areaDtoList = areaService.queryAreaListByParentId(parentId);

        String json = JSON.toJSONString(areaDtoList);
        response.getWriter().write(json);
    }

    // 展商页面局部刷新
    @RequestMapping(value = "/getProductShop")
    @ResponseBody
    public Result getProductShop(
            Integer customParentId,
            String customClassName,
            String topicName,
            String industryName,
            String province,
            String corpIdentities,
            String corpBusinessModel,
            String pageNum,
            String productTitle,
            String banPositionBack,
            String infoType){
        Result result = Result.ok();
        try {
            Integer pageSize = 10;
            Integer pageNumber = Integer.valueOf(pageNum);
            pageNumber = (pageNumber == null || pageNumber == 0) ? 1 : pageNumber;
            Map res = new HashMap();

            //产品分类 查询
            List<TypeDO> newList= Lists.newArrayList();
            if (customParentId!=null){
                TypeDO customClassDto= typeService.findById(customParentId);
                if(customClassDto==null){
                    res.put("crumbsList", newList);
                }else {
                    int customLevel = customClassDto.getLevel();
                    if (customLevel == 1) {
                        newList.add(customClassDto);
                    } else if (customLevel == 2) {
                        TypeDO parentCustomDto = typeService.findById(customClassDto.getParentId());
                        newList.add(parentCustomDto);
                        newList.add(customClassDto);
                    } else if (customLevel == 3) {
                        TypeDO secondParentCustomDto = typeService.findById(customClassDto.getParentId());
                        TypeDO firstParentCustomDto = typeService.findById(secondParentCustomDto.getParentId());
                        newList.add(firstParentCustomDto);
                        newList.add(secondParentCustomDto);
                        newList.add(customClassDto);
                    }
                }
            }
            res.put("crumbsList", newList);
            // 获取产品分类信息
            List<TypeDO> industryCustomClassDtoList;
            if(customParentId == null){
                // 一级分类
                industryCustomClassDtoList= typeService.customNames();
            }else {
                industryCustomClassDtoList = typeService.customName(customParentId);
                if(industryCustomClassDtoList.size()==0){
                    industryCustomClassDtoList= typeService.custom(customParentId);
                    for (int i = 0; i<industryCustomClassDtoList.size() ; i++) {
                        Integer ParentId = industryCustomClassDtoList.get(i).getParentId();
                        industryCustomClassDtoList = typeService.customName(ParentId);
                    }
                }else {
                    industryCustomClassDtoList = typeService.customName(customParentId);
                }
            }
            Integer finalCategoryId = customParentId;
            boolean present = industryCustomClassDtoList.stream().filter(c -> finalCategoryId.equals(c.getId())).findAny().isPresent();
            if(!present){
                customParentId = null;
            }
            res.put("industryCustomClassDtoList",industryCustomClassDtoList);
            // 获取主题专区信息
            List<TopicDO> industryTopicList=topicService.topicName();
            res.put("industryTopicList",industryTopicList);
            // 获取应用行业信息
            List<ApplicationClassDO> industryApplicationList=applicationClassService.applicationName();
            res.put("industryApplicationList",industryApplicationList);

            // 获取展商信息
            Page<CompanyExhibitorInformationVO> industryExhibitorList=companyExhibitorInformationService.exhibitorCompany(PageFactory.createPageInfo(pageNumber,pageSize),province.substring(0, 2),customClassName,corpIdentities,corpBusinessModel,productTitle,topicName,industryName,infoType);
            res.put("pageList", industryExhibitorList.getRecords());
            // 当前页面总页数
            Long allNum = industryExhibitorList.getTotal();
            res.put("allNum", allNum);

            res.put("pageS",industryExhibitorList.getSize());
            res.put("pageNum", pageNum);

            // 获取展品信息
            List<ExhibitDO> industryProductDtoList = exhibitService.getIndustryproduct();
            // 展品图片
            List<ExhibitDO> fistPictureList = new ArrayList<>();
            if(industryProductDtoList.size()>0){
                for (int i = 0; i <industryProductDtoList.size() ; i++) {
                    String fileId = industryProductDtoList.get(i).getImageId();
                    if (fileId == null) {
                        fistPictureList.add(industryProductDtoList.get(i));
                    } else {
                        //根据展品的UUID去查询相应的图片，用于展品展示
                        FileDO fileDO = fileService.getFile(fileId);
                        String picUrlStr = fileDO.getFileUrl();
                        if (picUrlStr.indexOf(";")==-1){
                            industryProductDtoList.get(i).setImageUrl(picUrlStr);
                            fistPictureList.add(industryProductDtoList.get(i));
                        }else{
                            String[] picOssUrlArr = picUrlStr.split(";");
                            industryProductDtoList.get(i).setImageUrl(picOssUrlArr[0]);
                            fistPictureList.add(industryProductDtoList.get(i));
                        }
                    }
                }
            }

            res.put("industryProductDtoList", fistPictureList);
            // 是否关注
            // 判断是否登录
            UserContext loginDoorUserDto=sessionUtil.getUserContext();
            // 判断用户有无关注
            if(loginDoorUserDto==null){
                Integer resFlag = 0;
                res.put("resFlag", resFlag);
                res.put("userId", "0");
            }else {
                Integer userId = loginDoorUserDto.getUserId();
                List<ExhibitorDO> userAttentionList = exhibitorService.findExhibitorAttention(userId);

                Integer resFlag = 0;
                if (userAttentionList.size() > 0) {
                    resFlag = 1;
                }
                res.put("resFlag", resFlag);
                res.put("userId", userId);
                res.put("userAttentionList", userAttentionList);
            }

            res.put("customParentId", industryCustomClassDtoList.size() == 0 ? "" : customParentId);
            res.put("finalCategoryId", finalCategoryId);
            res.put("topicName", topicName);
            res.put("industryName", industryName);
            res.put("province", province);
            res.put("banPositionBack",banPositionBack);
            result.setData(res);
        }catch (Exception e){
            result = Result.error("系统出错");
            e.printStackTrace();
        }
        return result;
    }
}
